<script setup lang="ts">
import { getCodeAPI, postLoginAPI } from '@/apis/common'
import { useUserstore } from '@/stores/uesr'
import { ref } from 'vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})

//

const showCountDown = ref(false)

const getMobileCode = async () => {
  await formRef.value?.validateField?.(['mobile'])
  showCountDown.value = true
  // 获取验证码
  const res = await getCodeAPI({ mobile: formData.value.mobile, type: 'login' })
  console.log(res)

  // 提示框
}

// 登录

// 表单数据
const formData = ref({
  mobile: '13230000011',
  code: '',
})

const isAgree = ref(false)
// 表单校验
// 2. 表单验证规则
const formRules = ref({
  mobile: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号' },
    ],
  },
  code: {
    rules: [
      { required: true, errorMessage: '请输入验证码' },
      { pattern: /^\d{6}$/, errorMessage: '验证码格式错误' },
    ],
  },
})
// 表单整体校验
const formRef = ref<UniHelper.UniFormsInstance>()
const handleLogin = async () => {
  const res = await formRef.value?.validate?.()
  // 协议检验
  if (!isAgree.value) {
    uni.showToast({
      title: '请先同意用户协议及隐私协议',
      icon: 'none',
    })
  }
  // 点击登录 请求接口
  const res1 = await postLoginAPI(formData.value)
  console.log(res1)
  //持久化存储
  const store = useUserstore()
  store.setToken(res1.data.token)
  // 提示框
  uni.showToast({
    title: '登录成功',
    icon: 'none',
  })
  uni.switchTab({ url: '/pages/index/index' })
}
</script>
s
<template>
  <uni-forms class="login-form" ref="formRef" :model="formData" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :maxlength="11"
        v-model="formData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        :maxlength="7"
        v-model="formData.code"
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
      />
      <text class="text-button" v-if="!showCountDown" @click="getMobileCode">获取验证码</text>
      <view v-else>
        <uni-countdown
          :show-day="false"
          :show-hour="false"
          :show-minute="false"
          :second="60"
          @timeup="showCountDown = false"
        />秒后重新发送
      </view>
    </uni-forms-item>
    {{ formData }}
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="handleLogin">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
@import '../styles.scss';
</style>
